<template>
    <div class="home">
        <img v-if="imgUrl" :src="imgUrl" alt />
        <van-uploader :after-read="afterRead" />
        <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <van-card
                v-for="item in shopList"
                :key="item.id"
                :num="item.count"
                :price="item.price"
                :desc="item.detail"
                :title="item.title"
                :thumb="item.image"
                @click="$router.push('/detail/' + item.id)"
            />
        </van-list>
    </div>
</template>

<script>
import { mapState, mapMutations, mapGetters, mapActions } from 'vuex'
import axios from '../../utils/request'
export default {
    data() {
        return {
            pageIndex: 1,
            pageSize: 10,
            loading: false,
            imgUrl: '',
            finished: false, // false 为完成 true 全部加载完毕
        }
    },
    computed: {
        shopList() {
            return this.$store.state.home.shopList
        },
        total() {
            return this.$store.state.home.total
        }
    },
    created() {
        this.pageChange()
    },
    methods: {
        // 辅助函数
        ...mapActions('home', ['SET_SHOP_LIST']), // 具名模块
        afterRead(file) {
            // 此时可以自行将文件上传至服务器
            const formData = new FormData(); // 创建一个表单对象
            formData.append('file', file.file) // 添加文件参数
            axios.post('/api/tools/saveavatar', formData).then(res => {
                this.imgUrl = res.data.file;
            })
        },
        // ...mapActions(['SET_SHOP_LIST']),
        async onLoad(e) {
            this.pageIndex += 1;
            await this.pageChange(this.pageIndex)
            // 当数据加载完 finished = true;
            if (this.shopList.length >= this.total) {
                this.finished = true; // 加载完毕
            }
            this.loading = false; // 等待异步完毕在变为false
        },
        pageChange(ind = 1) {
            this.pageIndex = ind;
            return this.SET_SHOP_LIST({ pageIndex: this.pageIndex, pageSize: this.pageSize })
            // return this.$store.dispatch('home/SET_SHOP_LIST', { pageIndex: this.pageIndex, pageSize: this.pageSize })
        }
    }
}
</script>

<style>
</style>